import axios from "axios";


const baseURL = 'http://127.0.0.1:3007' ;
const request = axios.create({
    baseURL: baseURL
});


//请求拦截器中带上token
request.interceptors.request.use(config => {
    let token=localStorage.getItem('token') || ''
    config.headers['Authorization'] = `${token}`;
    return config;
}, error => {
    return Promise.reject(error);
});

//响应拦截器，如果未授权，则跳转登录页面
axios.interceptors.response.use(
    response => response,
    error => {
      if (error.response.status === 401) {
        // 跳转至登录页面
        router.push('/login');
      }
  
      return Promise.reject(error);
    }
);

export function axiosPost(url, data,requestHead={
    headers: {
        "Content-Type": "application/json",
    },
}) {
    return new Promise((resolve, reject) => {
        request
            .post(url, data, )
            .then((response) => {
                resolve(response);
            })
            .catch((err) => {
                reject(err);
            });
    });
}

export function axiosGet(url, params = {}) {
    return new Promise((resolve, reject) => {
        request
            .get(url, {
                params: params,
            })
            .then((response) => {
                resolve(response);
            })
            .catch((err) => {
                reject(err);
            });
    });
}

export default request;